package server;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

import domain.Bill;
import domain.PriceStep;

import exceptions.NegativeValueException;
import exceptions.NoExistingPriceStepException;

public class BillingServerSecure extends UnicastRemoteObject implements BillingSecureInterface, BillAuctionInterface {

	private Bills bills;
	private PriceSteps pricesteps;

	public BillingServerSecure() throws RemoteException {
		bills = Bills.getInstance();
		pricesteps = PriceSteps.getInstance();
	}

	@Override
	public PriceSteps getPriceSteps() throws RemoteException {
		return pricesteps;
	}

	@Override
	public void createPriceStep(double startPrice, double endPrice, double fixedPrice, double variablePricePercent) throws RemoteException, NegativeValueException {
		double end = endPrice;
		if(end == 0){
			end = Double.MAX_VALUE;
		}



		if(startPrice < 0){
			throw new NegativeValueException("Startprice negative!");
		} if(end < 0){
			throw new NegativeValueException("Endprice negative!");
		} if(fixedPrice < 0){
			throw new NegativeValueException("Fixed Price negative!");
		} if(variablePricePercent < 0 || variablePricePercent > 100){
			throw new NegativeValueException("Variable Price not between 0 and 100!");
		} 
		PriceStep pricestep = new PriceStep(startPrice, end, fixedPrice, variablePricePercent);
		pricesteps.checkOverlapping(startPrice,end);
		pricesteps.add(pricestep);

	}

	@Override
	public void deletePriceStep(double startPrice, double endPrice) throws RemoteException, NoExistingPriceStepException {
		
		pricesteps.delete(startPrice,endPrice);

			
	}

	@Override
	public void billAuction(String user, long auctionID, double price) throws RemoteException {
		//vom auctionserver
		double fixedFee = 0;
		double variableFee = 0;
		double totalVariableFee = 0;
		double totalFee = 0;

		//		login auf auctionserver!
		System.out.println("billing auction, user: "+user+" id: "+auctionID+" price: "+price);

		PriceStep priceStep = pricesteps.getPriceStep(price);
		if(priceStep != null) {
			fixedFee = priceStep.getFixedPrice();
			variableFee = priceStep.getVariablePricePercent();
			//totalVariableFee = price - (price/(((Math.round(variableFee))/100)+1));
			//700/100*5,5
			totalVariableFee = (price/100)*variableFee;

			totalFee = fixedFee + totalVariableFee;
		}

			//getprice step
			
		
		Bill bill = new Bill(user, auctionID, price, fixedFee, totalVariableFee, totalFee);
		bills.add(bill);
		
	}

	@Override
	public Bill getBill(String user){
		//vom client
		return bills.getBill(user);

	}

}
